package com.cym.controller;

import java.util.ArrayList;
import java.util.List;

import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.ModelAndView;

import com.cym.model.Project;
import com.cym.model.User;
import com.cym.resp.ProjectResp;
import com.cym.service.ProjectService;
import com.cym.service.UserService;
import com.cym.sqlhelper.bean.Page;
import com.cym.utils.BaseController;
import com.cym.utils.BeanExtUtil;
import com.cym.utils.JsonResult;

import cn.hutool.core.util.StrUtil;

@Controller
@Mapping("/adminPage/project")
public class ProjectController extends BaseController {
	@Inject
	ProjectService projectService;
	@Inject
	UserService userService;
	@Mapping("")
	public ModelAndView index( ModelAndView modelAndView, Page pageReq, String keywords) {

		Page<Project> pageResp = projectService.search(pageReq, keywords);
		Page<ProjectResp> page = BeanExtUtil.copyPageByProperties(pageResp, ProjectResp.class);

		for (ProjectResp projectResp :(List<ProjectResp>) page.getRecords()) {

			projectResp.setUserList(userService.getByProjectId(projectResp.getId()));

			List<String> names = new ArrayList<>();
			for (User user : projectResp.getUserList()) {
				names.add(user.getTrueName() + "(" + userService.getTypeName(user.getType()) + ")");
			}
			projectResp.setUserNames(StrUtil.join("&nbsp;&nbsp;", names));
		}

		modelAndView.put("keywords", keywords);
		modelAndView.put("page", page);
		modelAndView.put("userList", sqlHelper.findAll(User.class));
		modelAndView.view("/adminPage/project/index.html");
		return modelAndView;
	}

	
	@Mapping("addOver")
	
	public JsonResult addOver(Project project, String[] userIds) {
		Project projectOrg = projectService.getByName(project.getName(),project.getId());
		if (projectOrg != null) {
			return renderError("此项目名已存在");
		}
		if (project.getName().equals("系统管理")) {
			return renderError("此项目名已存在"); 
		}

		projectService.insertOrUpdate(project, userIds);

		return renderSuccess();
	}

	@Mapping("detail")
	
	public JsonResult detail(String id) {
		Project project = sqlHelper.findById(id, Project.class);
		ProjectResp projectResp  = BeanExtUtil.copyNewByProperties(project, ProjectResp.class);
		
		projectResp.setUserList(userService.getByProjectId(projectResp.getId()));

		List<String> names = new ArrayList<>();
		for (User user : projectResp.getUserList()) {
			names.add(user.getName() + "(" + userService.getTypeName(user.getType()) + ")");
		}
		projectResp.setUserNames(StrUtil.join("&nbsp;&nbsp;", names));
		
		return renderSuccess(projectResp);
	}

	
	@Mapping("del")
	
	public JsonResult del(String id) {
		if (projectService.hasProjectFunction(id)) {
			return renderError("此项目已存在任务, 不可删除");
		}

		projectService.deleteById(id);

		return renderSuccess();
	}

}
